import React from 'react'
import CustomBreadcrumb from '../../components/CustomBreadcrumb/index'
import {Table, Button, Input, Modal, Tabs, Form, Row, Col, Select, Checkbox, message, Popconfirm,
DatePicker} from 'antd';
import {getRolePlucks, getRolesPermission, getUserPermissions} from "../../api/role";
import {addUser, getAdmins, getDetail, editUser, delUser} from "../../api/user";
import {getPermissions} from "../../api/permissions";
import {getShopPlucks} from "../../api/store";
import './index.css'

const {Search} = Input;
const {TabPane} = Tabs;
const {Option} = Select;
const { RangePicker } = DatePicker;
const InputGroup = Input.Group;


class Person extends React.Component {

    state = {
        selectedRowKeys: [], // Check here to configure the default column
        loading: false,
        modal1Visible: false,
        rolesList: [],
        data: [],
        permissions: [],
        checkAll: false,
        rolePermission: [],
        id: '',
        title: '',
        form: {},
        page: 1,
        size: 100,
        userPermission:[]
    };

    setModalVisible(modal1Visible) {
        this.setState({modal1Visible});
    }

    start = () => {
        this.setState({loading: true});
        // ajax request after empty completing
        setTimeout(() => {
            this.setState({
                selectedRowKeys: [],
                loading: false,
            });
        }, 1000);
    };

    onSelectChange = selectedRowKeys => {
        this.setState({selectedRowKeys});
    };

    componentDidMount() {
        this._getAdmins()
    }

    /**
     * 获取管理员列表
     */
    _getAdmins() {
        const page = this.state.page
        const size = this.state.size
        getAdmins(page, size).then((res) => {
            if (res.code < 400) {
                this.setState({
                    data: res.data.data
                })
            }
        })
    }

    /**
     * 添加
     * @returns {*}
     */
    add() {
        this._getRoles()
        this._getPermissions()
        this.setState({
            modal1Visible: true,
            id: '',
            title: '添加管理员',
            form: {}
        });
    }

    /**
     * 获取角色对应的权限
     */
    _getRolesPermission(id) {
        const ids = {
            role_ids: [id]
        }
        getRolesPermission(ids).then((res) => {
            if (res.data && res.data.length > 0) {
                const permissionData = res.data
                const permissions = this.state.permissions
                const newpermissions = permissions.map((item) => {
                    if (permissionData.includes(item.display_name)) {
                        item.checked = true
                        item.disabled = true
                    }
                    return item
                })
                this.setState({
                    permissions: newpermissions,
                    rolePermission: permissionData
                })
            } else {
                const permissionData = this.state.permissions
                const newpermissions = permissionData.map((item) => {
                    item.checked = false
                    item.disabled = false
                    return item
                })
                this.setState({
                    permissions: newpermissions,
                    rolePermission: [],
                    checkAll: false
                })
            }
        })
    }

    /**
     * 获取所有权限
     *
     */
    _getPermissions() {
        getPermissions().then((res) => {
            const permissions = res.data
            if (permissions.length > 0) {
                const per = permissions.map((item) => {
                    item.checked = false
                    item.disabled = false
                    return item
                })
                this.setState({
                    permissions: per
                })
            }

        })
    }

    /**
     * 获取所有角色
     * @returns {*}
     */
    _getRoles() {
        getRolePlucks().then((res) => {
            if (res.data) {
                const roleData = res.data
                const rolesList = []
                for (let index in roleData) {
                    var roles = {
                        id: index,
                        name: roleData[index]
                    }
                    rolesList.push(roles)
                }
                this.setState({
                    rolesList
                })
            }
        })
    }

    /**
     * 改变权限
     * @returns {*}
     */
    onChangeCheckbox = (e) => {
        const id = e.target.dataId
        const permissions = this.state.permissions
        var all = 0
        var none = 0
        for (let index in permissions) {
            all++
            if (permissions[index].id === id) {
                permissions[index].checked = !permissions[index].checked
            }
            if (permissions[index].checked) {
                none++
            }
        }
        let checkAll = true
        if (all !== none) {
            checkAll = false
        }
        this.setState({
            permissions,
            checkAll
        })
    }

    /**
     * 选择角色
     */
    handleSelectChange = (val) => {
        let id = val
        this.props.form.setFieldsValue({
            role_ids: val
        });
        this.setState({
            form: {
                roleId: val
            }
        })
        this._getRolesPermission(id)
    }
    /**
     * 全选
     * @returns {*}
     */
    onCheckAllChange = () => {
        this.setState({
            checkAll: !this.state.checkAll
        })
        var AllPermission = this.state.permissions
        var rolePermission = this.state.rolePermission
        if (!this.state.checkAll) {
            AllPermission = this.state.permissions.map((item) => {
                item.checked = true
                return item
            })
        } else {
            AllPermission = this.state.permissions.map((item) => {
                if (rolePermission.includes(item.display_name)) {
                    item.checked = true
                } else {
                    item.checked = false
                }
                return item
            })
        }
        this.setState({
            permissions: AllPermission
        })
    }
    /**
     * 添加表单
     * @returns {*}
     */
    submitForm = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                const role_ids = []
                role_ids.push(values.role_ids)
                delete values.role_ids
                if (values.password !== values.old_password) {
                    message.warning('密码不一致！')
                    return false
                }
                const permissionsSubmit = this.state.permissions
                // 修改之前的权限
                const oldUserPermission = this.state.userPermission
                const add_permission_ids = []
                const del_permission_ids = []
                permissionsSubmit.forEach((item) => {
                    if (item.checked && !item.disabled && !oldUserPermission.includes(item.display_name)) {
                        add_permission_ids.push(item.id)
                    }
                    if (!item.checked && oldUserPermission.includes(item.display_name)) {
                        del_permission_ids.push(item.id)
                    }
                })

                    const subData = Object.assign({}, values, {role_ids}, {add_permissions:add_permission_ids},
                        {delete_permissions:del_permission_ids})
                    // 根据id获取详情
                    const id = this.state.id
                    if (id) {
                        // 编辑
                        subData.id = id

                        this._editUser(subData)
                    } else {
                        //添加
                        delete subData.delete_permissions
                        this._addUser(subData)
                    }

            }
        })
    }

    /**
     * 添加用户
     * @returns {*}
     */
    _addUser(data) {
        addUser(data).then((res) => {
            if (res.code < 400) {
                message.success('添加成功!')
                this._getAdmins()
                this.setState({
                    modal1Visible: false,
                    checkAll: false
                })
            }
        })
    }

    /**
     * 修改用户
     * @param data
     */
    _editUser(data) {
        editUser(data).then((res) => {
            if (res.code < 400) {
                message.success('修改成功!')
                this._getAdmins()
                this.setState({
                    modal1Visible: false,
                    checkAll: false
                })
            }
        })
    }

    /**
     * 修改页面
     * @returns {*}
     */
    async edit(id) {
        await this._getDetail(id)
        await this._getRoles()
        await this._getPermissions()
        await this._getUserPermissions(id)
        this.setState({
            modal1Visible: true,
            title: '修改管理员',
            id,
            form: {}
        });
    }

    /**
     * 获取管理员详情
     * @returns {*}
     */
    _getDetail(id) {
        getDetail(id).then((res) => {
            if (res.code < 400) {
                const formData = res.data
                if (formData.user_roles.role_id) {
                    formData.roleId = formData.user_roles.role_id.toString()
                } else {
                    formData.roleId = ''
                }
                formData.password = '123456'
                formData.old_password = '123456'
                formData.role_ids = formData.user_roles.role_id
                const formField = this.props.form.getFieldsValue()
                Object.keys(formField).forEach((key) => {
                    formField[key] = formData[key]
                })
                this.props.form.setFieldsValue(formField)
                this.setState({
                    form: formData
                })
            }
        })
    }

    /**
     * 选择店铺
     * @returns {*}
     */
    handleSelectChangeShop = (val) => {
        this.props.form.setFieldsValue({
            shop_id: val
        });
    }

    /**
     * 获取店铺
     * @returns {*}
     */
    _getShopPlucks() {
        getShopPlucks().then((res) => {

        })
    }

    /**
     * 获取用户对应的权限
     * @returns {*}
     */
    _getUserPermissions(id) {
        getUserPermissions(id).then((res) => {
            if (res.code < 400) {
                if (res.data.user) {
                    const userPermission = res.data.user
                    const userRole = res.data.role
                    const allPermission = this.state.permissions
                    const allPermissions = allPermission.map((item) => {
                        if (userPermission.includes(item.display_name)) {
                            item.checked = true
                        }
                        if (userRole.includes(item.display_name)) {
                            item.disabled = true
                            item.checked = true
                        }
                        return item
                    })
                    this.setState({
                        permissions: allPermissions,
                        userPermission:userPermission
                    })
                }
            }
        })
    }

    /**
     * 删除用户
     * @returns {*}
     */
    delConfirm = (id) => {
        delUser(id).then((res) => {
                if (res.code < 400) {
                    this._getAdmins()
                    message.success('删除成功！');
                } else {
                    message.success('删除失败！');
                }
            }
        )
    }

    render() {
        const columns = [
            {
                title: '序号',
                width: 100,
                align: 'center',
                render: (text, record, index) => {
                    return (index + 1)
                }
            },
            {
                title: '名称',
                width: 100,
                align: 'center',
                dataIndex: 'username'
            },
            {
                title: '添加时间',
                width: 100,
                align: 'center',
                dataIndex: 'created_at'
            },
            {
                title: '操作',
                width: 100,
                key: 'action',
                align: 'center',
                render: (text, record) => (
                    <span>
                        <Button style={{marginRight: 10}} onClick={() => {
                            this.edit(record.id)
                        }}>修改</Button>
                        <Popconfirm
                            title="你确认要删除吗?"
                            onConfirm={() => {
                                this.delConfirm(record.id)
                            }}
                            okText="确定"
                            cancelText="取消"
                        >
                        <Button type="danger">删除</Button>
                        </Popconfirm>
                    </span>
                )

            }
        ];
        const {loading, selectedRowKeys} = this.state;
        const {getFieldDecorator} = this.props.form;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        return (
            <div>
                <CustomBreadcrumb arr={['管理员']}/>
                <div style={{marginBottom: 16}}>
                    <InputGroup compact style={{ borderBottom: '16px' }}>
                      <Button type="primary" onClick={this.start} disabled={!hasSelected} loading={loading}>
                          删除
                      </Button>
                      <Input placeholder="请输入管理员名称" style={{ width: 120, borderRight: '1px solid rgb(217,217,217)', borderTopRightRadius: '4px', borderBottomRightRadius: '4px' }}/>
                      <span className="changeDate">请输入日期:</span>
                      <RangePicker />
                      <Button type="primary" shape="circle" icon="search" />     
                    </InputGroup>
                </div>
                <Modal
                    title={this.state.title}
                    centered
                    width={1000}
                    destroyOnClose={true}
                    visible={this.state.modal1Visible}
                    onOk={() => this.submitForm()}
                    onCancel={() => this.setModalVisible(false)}
                >
                    <Tabs defaultActiveKey="1">
                        <TabPane tab="用户信息" key="1">
                            <Form>
                                <Row>
                                    <Col span={10}>
                                        <Form.Item label="选择角色">
                                            {getFieldDecorator('role_ids', {
                                                rules: [{required: true, message: '请选择角色!'}],
                                            })(
                                                <Row>
                                                    <Col span={20}>
                                                        <Select
                                                            placeholder="选择角色"
                                                            value={this.state.form.roleId}
                                                            onChange={this.handleSelectChange}
                                                        >
                                                            {
                                                                this.state.rolesList.map((item) => {
                                                                    return (<Option value={item.id}
                                                                                    key={item.id}>{item.name}</Option>)
                                                                })
                                                            }
                                                        </Select>
                                                    </Col>
                                                </Row>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={10}>
                                        <Form.Item label="用户名称">
                                            {getFieldDecorator('username', {
                                                rules: [{required: true, message: '请输入用户名称!'}]
                                            })(
                                                <Row>
                                                    <Col span={20}>
                                                        <Input defaultValue={this.state.form.username}
                                                                           placeholder="请输入用户名称"/></Col>
                                                </Row>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={10}>
                                        <Form.Item label="登陆密码">
                                            {getFieldDecorator('password', {
                                                rules: [{required: true, message: '请输入登陆密码!'}],
                                            })(
                                                <Row>
                                                    <Col span={20}> <Input type="password"
                                                                           defaultValue={this.state.form.password}
                                                                           placeholder="请输入登陆密码"/></Col>
                                                </Row>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={10}>
                                        <Form.Item label="确认密码">
                                            {getFieldDecorator('old_password', {
                                                rules: [{required: true, message: '请输入确认密码!'}],
                                            })(
                                                <Row>
                                                    <Col span={20}> <Input type="password"
                                                                           defaultValue={this.state.form.password}
                                                                           placeholder="请输入确认密码"/></Col>
                                                </Row>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={10}>
                                        <Form.Item label="真实姓名">
                                            {getFieldDecorator('name', {
                                                rules: [{required: true, message: '请输入真实姓名!'}],
                                            })(
                                                <Row>
                                                    <Col span={20}> <Input defaultValue={this.state.form.name}
                                                                           placeholder="请输入真实姓名"/></Col>
                                                </Row>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={10}>
                                        <Form.Item label="紧急联系人">
                                            {getFieldDecorator('urgent_name', {
                                                rules: [{required: true, message: '请输入紧急联系人!'}],
                                            })(
                                                <Row>
                                                    <Col span={20}> <Input defaultValue={this.state.form.urgent_name}
                                                                           placeholder="请输入紧急联系人"/></Col>
                                                </Row>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={10}>
                                        <Form.Item label="联系电话">
                                            {getFieldDecorator('urgent_phone', {
                                                rules: [{required: true, message: '请输入联系电话!'}],
                                            })(
                                                <Row>
                                                    <Col span={20}> <Input maxLength='11'
                                                                           defaultValue={this.state.form.urgent_phone}
                                                                           placeholder="请输入联系电话"/></Col>
                                                </Row>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={10}>
                                        <Form.Item label="选择店铺">
                                            {getFieldDecorator('shop_id')(
                                                <Row>
                                                    <Col span={20}>
                                                        <Select
                                                            placeholder="选择店铺"
                                                            onChange={this.handleSelectChangeShop}
                                                        >
                                                            {
                                                                this.state.rolesList.map((item) => {
                                                                    return (<Option value={item.id}
                                                                                    key={item.id}>{item.name}</Option>)
                                                                })
                                                            }
                                                        </Select>
                                                    </Col>
                                                </Row>
                                            )}
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Form>
                        </TabPane>
                        <TabPane tab="权限信息" key="2">
                            <div>
                                <div style={{borderBottom: '1px solid #E9E9E9'}}>
                                    <Checkbox
                                        indeterminate={this.state.indeterminate}
                                        onChange={this.onCheckAllChange}
                                        checked={this.state.checkAll}
                                    >
                                        全选
                                    </Checkbox>
                                </div>
                                <br/>
                                {
                                    this.state.permissions.map((item) => {
                                        return (
                                            <Checkbox onChange={this.onChangeCheckbox} disabled={item.disabled}
                                                      dataId={item.id}
                                                      key={item.id}
                                                      checked={item.checked}>{item.display_name}</Checkbox>)
                                    })
                                }

                            </div>
                        </TabPane>
                    </Tabs>,
                </Modal>
                <Table rowSelection={rowSelection} rowKey="id" columns={columns} dataSource={this.state.data}/>
            </div>
        );
    }
}

const PersonFrom = Form.create()(Person);
export default PersonFrom
